package cn.psvmc.cxzapi.service.customer;

import cn.psvmc.cxzapi.config.ConfigKey;
import cn.psvmc.cxzapi.constant.GlobalConstant;
import cn.psvmc.cxzapi.enums.ResultCode;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.mapper.customer.TCustomerAuthMapper;
import cn.psvmc.cxzapi.mapper.customer.TCustomerMapper;
import cn.psvmc.cxzapi.mapper.system.THelpMapper;
import cn.psvmc.cxzapi.model.common.CustomerEntity;
import cn.psvmc.cxzapi.model.common.SearchEntity;
import cn.psvmc.cxzapi.model.customer.TCustomer;
import cn.psvmc.cxzapi.model.customer.TCustomerAuth;
import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.response.ResultGenerator;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.JedisUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author ywx
 * @className TCustomerMyService
 * @description
 * @date 2024/9/3 22:31
 **/
@Service
@Slf4j
public class TCustomerMyService {
    @Resource
    private TCustomerMapper tCustomerMapper;
    @Resource
    private JedisUtil jedisUtil;
    @Resource
    private THelpMapper tHelpMapper;
    @Resource
    private ServiceUtil serviceUtil;
    @Resource
    private TCustomerAuthMapper customerAuthMapper;

    /**
     * @Description 登录
     * @Date 2024/8/29 21:42
     * @Author YWX
     * @Param [tCustomer]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    public Result login(CustomerEntity customer) {
        String response = ToolUtils.getLoginResult(JSON.toJSONString(customer));
        Map<String, String> mapResult = JSON.parseObject(response, Map.class);
        TCustomerMyService.log.info("登录参数：{}", JSON.toJSONString(customer));
        TCustomerMyService.log.info("登录参数mapResult：{}", JSON.toJSONString(mapResult));
        String mobile = mapResult.get("mobile");
        Map<String, Object> map = tCustomerMapper.findByPhone(mobile);
        String name = customer.getName();
        TCustomer tCustomer = new TCustomer();
        String[] userIdAndToken = ToolUtils.getUserIdAndToken(customer.getAuthCode());
        if (userIdAndToken != null && userIdAndToken.length == 3) {
            tCustomer.setUserid(userIdAndToken[0]);
            tCustomer.setOpenid(userIdAndToken[2]);
        }
        if (ToolUtils.isEmpty(tCustomer.getOpenid())) {
            throw new ServiceException("用户登录失败请重新登录！");
        }
        if (map == null) {
            tCustomer.setPhone(mobile);
            if (ToolUtils.isEmpty(name)) {
                name = "用户" + mobile.substring(mobile.length() - 4);
            }
            tCustomer.setName(name);
            String avatar = customer.getAvatar();
            if (ToolUtils.isEmpty(avatar)) {
                //1~30随机数
                avatar = ConfigKey.previewUrl + "avatar/avatar_" + (int) (Math.random() * 30 + 1) + ".png";
            }
            tCustomer.setAvatar(avatar);
            tCustomer.setScene(customer.getScene());
            tCustomerMapper.insert(tCustomer);
            map = new HashMap<>();
            map.put("name", name);
            map.put("customerid", tCustomer.getCustomerid());
            map.put("phone", tCustomer.getPhone());
            map.put("userid", tCustomer.getUserid());
            map.put("rversion", 1);
            map.put("avatar", avatar);
        } else {
            if ((userIdAndToken != null && (ToolUtils.isEmpty(map.get("userid")) || ToolUtils.isEmpty(map.get("openid"))))
                    || ToolUtils.isNotEmpty(name) && !name.equals(map.get("name"))) {
                tCustomer.setCustomerid(ToolUtils.objToInteger(map.get("customerid")));
                tCustomerMapper.updateById(tCustomer);
            }
        }

        Result result;
        //redis
        String token = ToolUtils.getToken();//获取token
        String key = getTokenKey(map.get("customerid"));//获取tokenKey
        boolean redis_rtn = jedisUtil.set(key, token, ConfigKey.redisdatatime);
        if (!redis_rtn) {
            ResultCode code = ResultCode.TOKEN_ADD_ERROR;
            result = ResultGenerator.genFailResult(code);
        } else {
            map.put("Cxz-Token-Key", key);
            map.put("Cxz-Token-Value", token);
            result = ResultGenerator.genSuccessResult("登录成功！", map);
        }
        return result;
    }

    private String getTokenKey(Object userid) {
        return GlobalConstant.TAG_CUSTOMER + userid;
    }

    /**
     * @Description 帮助中心列表
     * @Date 2024/8/29 22:29
     * @Author YWX
     * @Param [entity]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> listHelp(SearchEntity entity) {
        return tHelpMapper.listAll(entity);
    }

    /**
     * @Description 补充用户资料
     * @Date 2025/1/22 23:24
     * @Author YWX
     * @Param [auth]
     * @Return void
     **/
    public void updateUserProfile(TCustomerAuth auth) {
        Integer customerId = serviceUtil.getCustomerId();
        auth.setCustomerid(customerId);
        Map<String, Object> map = customerAuthMapper.findByCustomerId(customerId);
        if (map != null && map.containsKey("caid")) {
            auth.setCaid(ToolUtils.objToInteger(map.get("caid")));
            customerAuthMapper.updateById(auth);
        } else {
            customerAuthMapper.insert(auth);
        }
    }
}
